package control;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import util.Encoded;

import dao.UserData;

/**
 * Servlet implementation class Login
 */
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Login() {
        super();
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		UserData ud = new UserData();
		HttpSession session = request.getSession();
		String un = request.getParameter("email");
		String pwd = request.getParameter("passwd");
		String rem = request.getParameter("remem");
		if (un.equals("") || un.equals("")) {
			response.sendRedirect("index.jsp");
		}
		String encode = Encoded.getSHA1(pwd);
		boolean log = ud.checkLogin(un, encode);
		if (log) {
			session.setAttribute("email", un);
			if (rem != null) {
				Cookie userCookie = new Cookie("email", un);
				userCookie.setMaxAge(60 * 60 * 24 * 30);
				response.addCookie(userCookie);
			}
			response.sendRedirect("index.jsp");
		} else {
			session.setAttribute("thongbao", "Đăng Nhập không thành công");
			response.sendRedirect("failLogin.jsp");
		}
	}
				
}
